<template>
	<el-dialog :visible.sync="options.showDialog" width="600px" class="upload">
		<h3 class="upload-title">{{options.title}}</h3>
		<div class="upload-content">
			<el-upload ref="uploads" :limit="9" action=""
				:before-upload="beforeUpload" :auto-upload="false" :file-list="options.fileList">
				<span slot="trigger" class="el-icon-folder-add"></span>
			</el-upload>
		</div>
		<div class="upload-btn">
			<el-button style="margin-left: 10px;width: 80px;" size="mini" type="success" @click="submitUpload"
				>上传</el-button>
		</div>
	</el-dialog>
</template>

<script>
	export default {
		props: {
			options: {
				require: true,
				type: Object
			}
		},
		data() {
			return {
				fileName: '', //被上传的文件名
			}
		},
		methods: {
			//上传前校验
			beforeUpload(file) {
				const loading = this.$loading({
					lock: true,
					text: '文件正在上传中。。。',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				console.log(file);
				this.fileName = file.name;
				const type = file.name.substring(file.name.lastIndexOf('.') + 1);
				console.log(type);
				if (type != 'png' && type != 'jpg' && type != 'jpeg' && type != 'docx' && type != 'pdf') {
					this.$message({
						message: '请上传png、jpg、jpeg、docx、pdf类型的文件！',
						type: 'warning'
					})
					return false;
				}
				let reader = new FileReader();
				reader.readAsDataURL(file);
				let fileFormData = new FormData();
				fileFormData.append('file', file);
				if (type == 'pdf') {
					fileFormData.append('condition', 2);
				} else if (type == 'docx') {
					fileFormData.append('condition', 1);
				} else {
					fileFormData.append('condition', 3);
				}
				fileFormData.append('librarianId', this.options.userInfo.librarianId);
				this.$telAxios('/v1/librarian/GetUrl', {
					method: 'post',
					data: fileFormData,
					headers: {
						'content-type': 'application/x-www-form-urlencoded'
					}
				}).then(res => {
					console.log(res);
					if (res.data.code === 1000) {
						this.$message({
							message: '上传成功！',
							type: 'success'
						})
						loading.close();
						this.$emit('updateView', this.fileName);
						this.$emit('updateViews', res.data.data);
					} else {
						this.$message({
							message: '文件上传失败，请重新上传！',
							type: 'warning'
						})
					}
				})
			},
			//手动上传文件
			submitUpload() {
				this.$refs.uploads.submit();
			}
		},
	}
</script>

<style scoped="scoped">
	.upload .upload-title {
		height: 60px;
		line-height: 60px;
		text-align: center;
		font-size: 16px;
		border-bottom: 1px solid #D2D2D2;
	}

	.upload-content {
		width: 500px;
		margin: 20px auto;
		overflow: hidden;
	}

	.upload .el-icon-folder-add {
		font-size: 30px;
		width: 100px;
		height: 100px;
		text-align: center;
		line-height: 100px;
		border: 1px solid #000;
		margin: 0 20px 20px;
		float: left;
	}

	.upload-btn {
		text-align: center;
		padding: 20px 0;
	}
</style>
